package org.com.windoweasyconstructor;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.ArrayList;
import java.util.Iterator;

import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import javax.swing.Timer;

public class Aplicacao extends JFrame implements WindowListener {
	
	private static final long serialVersionUID = -3832447757772430775L;
	
	/**
	 * Instância da classe <code>Menu</code> criada com o intuito de montar os menus dinamicamente.
	 */
	private Menu menu = new Menu();
	
	/**
	 * Construtor padrão de <code>Aplicacao</code>.
	 *
	 */
	public Aplicacao() {
		
	}
	
	/**
	 * Configura o <code>JDialog</code> da aplicação, assim como chama o método <code>setVisible</code>
	 * para dar início à visualização da mesma. 
	 *
	 */
	public void initComponents() {
		this.montaMenu();
		
		super.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		super.setJMenuBar(menu);
		super.setMinimumSize(new Dimension(800,600));
		super.setVisible(true);
		super.addWindowListener(this);
	}
	
	public void windowClosing(WindowEvent e) {

		JOptionPane.showMessageDialog(null, "Saindo...");
        //A pause so user can see the message before
        //the window actually closes.
		ActionListener task = new ActionListener() {
            boolean alreadyDisposed = false;
            public void actionPerformed(ActionEvent e) {
                if (isDisplayable()) {
                    alreadyDisposed = true;
                    dispose();
                }
            }
        };
        Timer timer = new Timer(500, task); //fire every half second
        timer.setInitialDelay(2000);        //first delay 2 seconds
        timer.setRepeats(false);
        timer.start();
    }

	/**
	 * Construção do menu.
	 *
	 */
	@SuppressWarnings("unchecked")
	private void montaMenu() {
		String[] jMenus = { 
				"Arquivo", 
				"Editar", 
				"Exibir", 
				"Formatar", 
				"Ajuda" 
		};
		
		String[] jMenusMnemonic = {
				"A", 
				"E", 
				"x", 
				"F", 
				"u" 
		};
		
		String[] arquivoItens = { 
				"Novo", 
				"Abrir", 
				"" , 
				"Salvar", 
				"Salvar Como",
				"", 
				"Sair" 
		};
		
		KeyStroke[] arquivoItensAccelerator = {
				KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK),
				KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK),
				KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK),
				KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.SHIFT_MASK + ActionEvent.CTRL_MASK),
				KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK)
		};
		
		String[] editarItens = { 
				"Selecionar Tudo", 
				"", 
				"Localizar", 
				"Localizar e Substituir" 
		};
		
		KeyStroke[] editarItensAccelerator = {
				KeyStroke.getKeyStroke(KeyEvent.VK_T, ActionEvent.CTRL_MASK),
				KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.CTRL_MASK),
				KeyStroke.getKeyStroke(KeyEvent.VK_R, ActionEvent.CTRL_MASK)
		};
		
		ActionListener[] eventosEditar = {new EvtSelecionarTudo(),new EvtLocalizar(),new EvtLocalizarESubstituir()};
				
		menu.addJMenus(toArrayList(jMenus), toArrayList(jMenusMnemonic));
		menu.addJMenuItems("Arquivo", toArrayList(arquivoItens), toArrayList(arquivoItensAccelerator));
		menu.addJMenuItems("Editar", toArrayList(editarItens), toArrayList(editarItensAccelerator));
		menu.addEventos("Editar", toArrayList(editarItens), toArrayList(eventosEditar));
		menu.getJMenuItem("Arquivo", "Sair").addActionListener(new EvtSair());
	}
	
	/**
	 * Recebe um vetor de <code>Object</code>s e retorna um <code>Iterator</code>, que é
	 * a <b><code>interface</code></b> aceita pelos métodos de <code>Menu</code>.
	 * 
	 * @param itens
	 * @return <code>Iterator</code> contendo os itens do vetor	
	 * 		   passado ao método.
	 */
	@SuppressWarnings("unchecked")
	private Iterator toArrayList(Object[] itens) {
		ArrayList list = new ArrayList();
		for (int i = 0; i < itens.length; i++) {
			list.add(itens[i]);
		}
		return list.iterator();
	}
	
	//classes internas dos eventos gerados por alguns menus
	private class EvtSair implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			Integer answer = JOptionPane.showConfirmDialog(null, "Você deseja realmente sair?");
			if (answer.equals(0)) dispose();
		}	
	}
	
	private class EvtSelecionarTudo implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			JOptionPane.showMessageDialog(null, "...selecionar tudo");
		}	
	}
	
	private class EvtLocalizar implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			JOptionPane.showMessageDialog(null, "...localizar");
		}	
	}
	
	private class EvtLocalizarESubstituir implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			JOptionPane.showMessageDialog(null, "...localizar e substituir");
		}	
	}
	
	public static void main(String args[]) {
		/*try { //alterando o Look and Fell para o padrão do sistema utilizado
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (Exception e) {}*/
		
		Aplicacao aplicacao = new Aplicacao();
		aplicacao.initComponents();
	}
	//fim

	//@Override
	public void windowClosed(WindowEvent e) {
        //This will only be seen on standard output.
		//JOptionPane.showMessageDialog(null, "WindowListener method called: windowClosed.");
    }

	//@Override
    public void windowOpened(WindowEvent e) {
    	//JOptionPane.showMessageDialog(null, "WindowListener method called: windowOpened.");
    }

	//@Override
    public void windowIconified(WindowEvent e) {
    	//JOptionPane.showMessageDialog(null, "WindowListener method called: windowIconified.");
    }

	//@Override
    public void windowDeiconified(WindowEvent e) {
    	//JOptionPane.showMessageDialog(null, "WindowListener method called: windowDeiconified.");
    }

	//@Override
    public void windowActivated(WindowEvent e) {
    	//JOptionPane.showMessageDialog(null, "WindowListener method called: windowActivated.");
    }

	//@Override
    public void windowDeactivated(WindowEvent e) {
    	//JOptionPane.showMessageDialog(null, "WindowListener method called: windowDeactivated.");
    }

} //fim de Aplicacao